<?php

/**

 * Created by PhpStorm.

 * User: Administrator

 * Date: 2018/11/22

 * Time: 16:59

 */



namespace app\console\controller;

use think\Db;

use think\Request;

use think\Session;

use think\Loader;

use think\Url;

class Salesman

{

    /**

     * @return array|mixed|\think\response\View

     * 业务员管理

     */

    public function my_team()
    {

        $param = Request::instance()->param();
        $where = [];
        if(!empty($param['title'])) $where['m.username|m.telephone|m.nickname'] = ['like','%'.$param['title'].'%'];
        if (!empty($param['interval_timer'])) {
            $interval_timer = explode(' / ', $param['interval_timer']);
            $where['m.create_time'] = ['between time', [strtotime($interval_timer[0]), strtotime($interval_timer[1])]];
        }
        $data = Db::name('salesman s')
            ->join('manager m','s.manage_id = m.id','left')
            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')
            ->where('m.level',4)
            ->where($where)
            ->select()->toArray();

        if(!empty($data)){
            foreach ($data as $k => &$v){
                $v['member_count'] = Db::name('share_member s')->join('member m','m.id=s.member_id')->where('manage_id',$v['manage_id'])->count();
                $v['son_count'] = 1;
                $v['telephone'] = hideStr($v['telephone'],1,6);
            }
        }


        $parent_id = 0;
        $w = [];
        $auding_status = Db::name('manager m')->where('m.id',session('manage_id'))->join('auth_group ag','m.level = ag.id')->value('auding_status');
        if($auding_status == 1){
            $parent_id = session('manage_id');
            $w['s.manage_id'] = ['eq',\session('manage_id')];
        }
        if(!empty($param['salesman_id'])) $parent_id = $param['salesman_id'];

        $data = getMenuTree1($data,$parent_id);

        $sl = Db::name('salesman s')
            ->join('manager m','s.manage_id = m.id','left')
            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')
            ->where('m.level',4)
            ->where($w)
            ->select()->toArray();

        if(isset($param['export'])){
            $this->push($data);
        }
        return view('',['data' => $data,'sl' => $sl]);

    }

    /**
     * 公共salesman
     */
    public static function salesman_public($type_pk_id,$type,$salesman_id = 0)
    {
        $data = Db::name('salesman s')
            ->join('manager m', 's.manage_id = m.id', 'left')
            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')
            ->where('m.level', 4)
            ->select()->toArray();

        if (!empty($data)) {
            foreach ($data as $k => &$v) {
                $v['telephone'] = hideStr($v['telephone'], 1, 6);
                $v['per'] = Db::name('salesman_price')->where('type',$type)->where('salesman_id',$v['id'])->where('type_pk_id',$type_pk_id)->value('per');
            }
        }
        $data = getMenuTree1($data,$salesman_id);
        return $data;
    }

    public function push($data,$name = '业务员导出')
    {

        set_time_limit(0);
        ini_set('memory_limit', '1024M');
        error_reporting(E_ALL);
        date_default_timezone_set('Asia/Shanghai');

        import('phpoffice.phpexcel.Classes.PHPExcel', EXTEND_PATH, '.php');
        $objPHPExcel = new \PHPExcel();

        /*以下是一些设置 ，什么作者  标题啊之类的*/
        $objPHPExcel->getProperties()->setCreator("管理员")
            ->setLastModifiedBy("管理员")
            ->setTitle("电话本导出")
            ->setSubject("数据EXCEL导出")
            ->setDescription("备份数据")
            ->setKeywords("excel")
            ->setCategory("result file");
        $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
            ->setCellValue('A1', 'ID')
            ->setCellValue('B1', '业务员名称')
            ->setCellValue('C1', '业务员电话')
            ->setCellValue('D1', '创建时间')
            ->setCellValue('E1', '用户数量')
           ;
        $sheet1 = ['A', 'B', 'C', 'D', 'E'];

        for ($x = 0; $x < count($sheet1); $x++) {
            $objPHPExcel->getActiveSheet()->getStyle($sheet1[$x] . '1')->applyFromArray(
                array(
                    'font'      => array(
                        'bold' => true
                    ),
                    'alignment' => array(
                        'horizontal' =>
                            \PHPExcel_Style_Alignment::HORIZONTAL_CENTER
                    )
                )
            );
        }

        /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/

        $n = 0;
        foreach ($data as $v) {

            $num = $n + 2;
            $objPHPExcel->setActiveSheetIndex(0)
                //Excel的第A列，shop_name是你查出数组的键值，下面以此类推
                ->setCellValue('A' . $num, "\t".$v['id']."\t")
                ->setCellValue('B' . $num, str_repeat('--',$v['level']).$v['nickname'])
                ->setCellValue('C' . $num, "\t".$v['telephone']."\t")
                ->setCellValue('D' . $num, $v['create_time'])
                ->setCellValue('E' . $num, $v['member_count'])
            ;
            $n++;
        }

        $objPHPExcel->getActiveSheet(0)->setTitle('业务员导出');
        $objPHPExcel->setActiveSheetIndex(0);

        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;charset=utf-8;filename="' . $name . '.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output');
        exit;
    }




    public function update($id){

        if(Request::instance()->isPost()){



            $ret = Db::name('salesman')->fetchSql(false)->where('manage_id',$id)->update(['parent_id' => Request::instance()->param('parent_id')]);



            if($ret !== false){

                win('修改成功',Url::build('my_team'));

            }

            fail('修改失败');

        }

        $data = Db::name('salesman s')

            ->join('manager m','s.manage_id = m.id','left')

            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')

            ->where('m.level',4)

            ->select()->toArray();

        $info = Db::name('salesman s')

            ->join('manager m','s.manage_id = m.id','left')

            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')

            ->where('m.level',4)

            ->where('manage_id',$id)

            ->find();



        $data = getMenuTree1($data,0);



        return view('',['data' => $data,'item' => $info]);

    }



    /**

     * @return array|mixed|\think\response\View

     * 我的信息

     */

    public function my_information()

    {

        $data = Db::name('manager')->where('id', Session::get('manage_id'))->find();

        $order_number = $data['id'];

        Loader::import('phpqrcode.phpqrcode', EXTEND_PATH);

        $object = new \QRcode();

        $path = ROOT_PATH . 'public/salesman/' . $order_number . '.png';

        //第二个参数false的意思是不生成图片文件，如果你写上‘picture.png’则会在根目录下生成一个png格式的图片文件

        $url = Request::instance()->domain().'/index.php/mobile/user_port/share_member/manage_id/'.$data['id'];

        $ret = $object->png($url, $path, 10, 10, 2);

        $son = Db::name('salesman s')

            ->join('manager m','s.manage_id = m.id','left')

            ->field('m.username,m.create_time,s.*,m.id,m.telephone')

            ->select()->toArray();

        $parent_id = 0;

        $auding_status = Db::name('manager m')->where('m.id',session('manage_id'))->join('auth_group ag','m.level = ag.id')->value('auding_status');

        if($auding_status == 1){

            $parent_id = session('manage_id');

        }

        $son_data = getMenuTree1($son,$parent_id);

        $share_number = Db::name('share_member')->where('manage_id',Session::get('manage_id'))->count();

        return view('', ['data' => $data,'son_data' => $son_data,'share_number' => $share_number]);

    }



    public function member($id){

        $member_share = Db::name('share_member sm')

            ->join('member m','sm.member_id = m.id')

            ->field('m.*,sm.manage_id')

            ->where('manage_id',$id)

            ->select();




        $share_count = Db::name('share_member')->where('manage_id',$id)->count();
		$arr=array();
		//print_r(($member_share));
		foreach($member_share as &$v1)
		{


				 $member_amount=Db::name('member_distribution_records')->where('member_id',$v1['id'])->group('order_number')->select();
				  $amount=0;
				 if($member_amount)
				 {
						 foreach ($member_amount as $v)
						 {
						 $amount=$amount+$v['amount'];
						 
						 }
				 }
            if(\session('auding_status') == 1){
                $v1['username'] = hideStr($v1['username'],3,4);
            }
				// $v1['amount']=$amount;
		    $arr[]=array("id"=>$v1['id'],"username"=>$v1['username'],"real_name"=>$v1['real_name'],"sex"=>$v1['sex'],"id_number"=>$v1['id_number'],"is_certification"=>$v1['is_certification'],"level"=>$v1['level'],"create_time"=>$v1['create_time'],"amount"=>$amount,"nickname"=>$v1['nickname']);
		 }
		 		//halt($arr);

        return view('', ['member_share' => $arr]);

    }


   public function orderlook($id)
   {
    
	
	       $where = [];
     
            $where['mem.id'] = ['eq',$id];
      
       
      
      
        $data = Db::name('member_distribution_records mdr')
            ->join('manager m','mdr.manage_id = m.id','left')
            ->join('member mem','mdr.member_id = mem.id','left')
            ->where($where)
            ->field('mdr.manage_id,m.username manage_name,mem.username me,mdr.*')
			->group('mdr.order_number')
            ->order('mdr.create_time desc')
            ->paginate(10);
        $new_data = $data->toArray();
        foreach ($new_data['data'] as &$item){
            if(\session('auding_status') == 1){
            $item['me'] = hideStr($item['me'],3,4);
            }
                $item['goods_title'] = '';
                if($item['order_type']==1){
                    //根据订单号查询订单下面商品
                    $order_goods = Db::name('order_goods')
                        ->where('order_number',$item['order_number'])
                        ->select();
                    $str = '';
                    foreach ($order_goods as $value){
                        $str .= $value['title'].'/';
                    }
                    $new_str=substr($str,0,strlen($str)-1);
                    $item['goods_title'] = $new_str;
                }

        }
        $order_count = Db::name('member_distribution_records mdr')
            ->join('manager m','mdr.manage_id = m.id','left')
            ->where($where)
            ->field('m.username manage_name,mem.username,mdr.*')
            ->join('member mem','mdr.member_id = mem.id','left')->count();
        $member_count = Db::name('member_distribution_records mdr')
            ->join('manager m','mdr.manage_id = m.id','left')
            ->where($where)
            ->field('m.username manage_name,mem.username,mdr.*')
            ->join('member mem','mdr.member_id = mem.id','left')->count('mdr.member_id');
        $price = Db::name('member_distribution_records mdr')
            ->join('manager m','mdr.manage_id = m.id','left')
            ->where($where)
            ->field('m.username manage_name,mem.username,mdr.*')
            ->join('member mem','mdr.member_id = mem.id','left')->sum('price');//分销金额
        $all_date = Db::name('salesman s')
            ->join('manager m','s.manage_id = m.id','left')
            ->field('m.username,m.create_time,s.*,m.id,m.telephone')
            ->select()->toArray();
        $parent_id = 0;
        if(session('auding_status') == 1){
            $where['m.id'] = ['eq',Session::get('manage_id')];
        }
        if(session('auding_status') == 1){
            $parent_id = Session::get('manage_id');
        }
        $son_data = count(getMenuTree1($all_date,$parent_id));
        $salesman = Db::name('salesman s')
            ->join('manager m','s.manage_id = m.id','left')
            ->where('m.level',4)
            ->field('m.username,m.create_time,s.*,m.id,m.telephone')
            ->select()->toArray();

        return view('', ['data' => $data,'new_data'=>$new_data,'order_count' => $order_count,'price' => $price,'member_count' => $member_count,'son_data' => $son_data,'salesman' => $salesman]);
	
   
   }
    
	
	/**

     * @param $member_id

     * @return array

     * 我的我二维码

     */
	 

    public function update_level($manage_id)

    {

        if(Request::instance()->isPost()){

            $son = Db::name('salesman')->where('parent_id',$manage_id)->select();//当前管理唯一子集

            $new_parent_id = Request::instance()->param('parent_id');

            foreach ($son as $k => $v){

                Db::name('salesman')->where('manage_id',$v['manage_id'])->update(['parent_id' => $new_parent_id]);

            }



            win('修改成功',Url::build('my_team'));

        }





        $son = Db::name('salesman s')

            ->join('manager m','s.manage_id = m.id','left')

            ->field('m.username,m.nickname,m.create_time,s.*,m.id,m.telephone')

            ->where('m.level',4)

            ->select()->toArray();

        $son_str = implode(',',sonPath($son,$manage_id,true));



        $son_data = getMenuTree1($son,0);

        $info = Db::name('salesman s')

            ->where('s.manage_id',$manage_id)

            ->find();



    return view('',['son_date' => $son_data,'son_str' => $son_str,'info' => $info]);

    }

}